// pages/maintenance/subOrder/subOrder.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    subReportOrderData:{
      vin: "", 
      engineNo: "", 
      plateNo: "", 
      drivingLicenseUrl: "", 
      reportType: "",
      standardname2: ""
    },
    detailAmount:{
      balance:0,
      consumerScore:0,
      cumulativeConsumerScore:0,
      economizeAmount:0
    },
    orderPrice:{
      originalPrice:0,
      actualPrice:0,
    },
    orderSubData:{
      consumerScore:0, // 使用的积分 被68整除
      balance: 0, //余额支付的金额
      wxpayAmount: 0, //微信需要支付的金额。
    },
    usePayType:{
      useBalance: false,
      useConsumerScore: false,
      useWechat: false,
      useBalanceAndWechat: false
    },
    orderInfo:{
        orderNo:'',
        orderStatus: 0,
        payInfo:{}
    },
    amountManage: false // 能否使用积分余额
  },

  /**
   * 生命周期函数--监听页面加载
   */
  doNothing(){},
  onShow: function (options) {
    this.InitUserStatus();
  },
  // 检查一下登录状态。
  async InitUserStatus(){
      app.showLoading("获取用户信息");
      await app.checkToken();
      this.InitUserInfo();
      wx.hideLoading();
  },
  InitUserInfo(){
      let userInfo = app.globalData.userInfo;
      // 这里再验证一遍权限。
      console.log('userInfo',userInfo);
      if(userInfo.roleList.indexOf('amountManage') != -1){
        this.setData({
          'amountManage': true
        })
      }
      let subReportOrderData = app.globalData.subReportOrderData;
      // let subReportOrderData = {
      //   vin: "ZFFLJ65E690168516", 
      //   engineNo: "F1361B150329", 
      //   plateNo: "桂AP6P27", 
      //   drivingLicenseUrl: "https://zzsourcecar.oss-cn-hangzhou.aliyuncs.com/report/211218/57727ead03984f5dba385ab87e377a7do.?Expires=3220924258&OSSAccessKeyId=LTAI4GBcZtMnrVQ72WG22fri&Signature=IXfhRd2LVPZkIe1rPKXCx3dkgVo%3D",
      //   reportType: "c300InsuranceReport",
      //   standardname2: "LFFLJ65E"
      // };
      if(null == subReportOrderData){
        app.showNoAuthOrNoGrant('缺失重要参数，请重试');
        return;
      };
      // 正常查询
      if(subReportOrderData.reportType.indexOf('c300') != -1){
        subReportOrderData.dataFrom = "车三百";
      }else{
        subReportOrderData.dataFrom = "查博士";
      }
      this.setData({
        'subReportOrderData': subReportOrderData
      });
      // 获取用户的基础账户信息
      this.dealerAmountInfo();
      this.reportPrice();
      // if (userInfo.roleList.indexOf('reportApplyAudit') == -1) {
      //     app.showNoAuthOrNoGrant('您无权操作查看此页面');
      //     return;
      // }else{
      // }
  },
  jumpToWallet(){
    wx.navigateTo({
      url: '/pages/me/wallet/wallet?show=recharge',
    })
  },
  copyText: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },
  reportPrice(){
    app.sHttp.reportPrice(this.data.subReportOrderData).then(res =>{
      let orderSubData = this.data.orderSubData;
      res.result.actualPrice = (res.result.actualPrice).toFixed(2);
      res.result.originalPrice = (res.result.originalPrice).toFixed(2);
      orderSubData['jiesheng'] = (res.result.originalPrice - res.result.actualPrice).toFixed(2);
      orderSubData.wxpayAmount = res.result.actualPrice;
      this.setData({
        'orderPrice': res.result,
        'orderSubData': orderSubData
      })
    },err=>{
      app.error(err.msg);
      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        })
      }, 1500);
    })
  },
  dealerAmountInfo(){
    app.sHttp.dealerAmountInfo().then(res=>{
      this.setData({
        'detailAmount': res.result
      })
    },err=>{
      app.error(err.msg);
    })
  },
  useBalanceAndWechat(e){
    let self = this;
    this.setData({
      'usePayType.useBalanceAndWechat': !self.data.usePayType.useBalanceAndWechat
    });
  },
  useConsumerScore(e){
    console.log(e)
    this.setData({
      'usePayType.useConsumerScore': e.currentTarget.dataset.value
    });
    this.CalculatePrice();
  },
  useBalanceOrConsumerScore(e){
    let type = e.currentTarget.dataset.type;
    if(type == 'useBalance'){
      let useBalance = this.data.usePayType.useBalance;
      if(!useBalance){
        this.setData({
          'usePayType.useBalance': true,
          'usePayType.useWechat': false
        })
      }else{
        this.setData({
          'usePayType.useBalance': false
        })
      }
    } 
    if(type == 'useWechat'){
      let useWechat = this.data.usePayType.useWechat;
      if(!useWechat){
        this.setData({
          'usePayType.useWechat': true,
          'usePayType.useBalance': false
        })
      }else{
        this.setData({
          'usePayType.useWechat': false
        })
      }
    };
    this.CalculatePrice();
  },
  CalculatePrice(){
    app.showLoading('计算金额');
    //优先使用余额 其次积分 其次 微信支付。
    let usePayType = this.data.usePayType;
    let detailAmount = this.data.detailAmount;
    let actualPrice = this.data.orderPrice.actualPrice; // 剩余的需要计算的价格
    let orderSubData = {
      balance:0,
      consumerScore:0,
      wxpayAmount: actualPrice
    };
    if(usePayType.useConsumerScore){ //使用积分
      if(orderSubData.wxpayAmount > 0){
        let canDeductionMoney = parseInt(detailAmount.consumerScore/68);
        let zhengshuWxpayAmount =  parseInt(orderSubData.wxpayAmount);
        if(canDeductionMoney - zhengshuWxpayAmount >= 0){
          orderSubData.consumerScore = zhengshuWxpayAmount*68;
          orderSubData.wxpayAmount = orderSubData.wxpayAmount - zhengshuWxpayAmount;
        }else{
          orderSubData.consumerScore = canDeductionMoney*68;
          orderSubData.wxpayAmount = orderSubData.wxpayAmount - canDeductionMoney;
        }
      }
    }else{
      orderSubData.consumerScore = 0;
    };
    if(usePayType.useBalance){ //使用余额。
      if(orderSubData.wxpayAmount > 0){
        if(detailAmount.balance - orderSubData.wxpayAmount >= 0){
          orderSubData.balance = orderSubData.wxpayAmount;
          orderSubData.wxpayAmount = 0;
        }else{
          orderSubData.balance = detailAmount.balance;
          orderSubData.wxpayAmount = orderSubData.wxpayAmount - detailAmount.balance;
        }
      }
    }else{
      orderSubData.balance = 0;
    };
    console.log(orderSubData);
    orderSubData.wxpayAmount = (orderSubData.wxpayAmount-0).toFixed(2);
    orderSubData['jiesheng'] = (this.data.orderPrice.originalPrice - orderSubData.wxpayAmount).toFixed(2);
    this.setData({
      'orderSubData':orderSubData
    });
    wx.hideLoading();
  },
  // 提交订单
  preparePay(){
    try {
      let subData = app.deepCopy(this.data.subReportOrderData);
      delete subData.standardname2;
      subData['consumerScore'] = this.data.orderSubData.consumerScore;
      subData['balance'] = this.data.orderSubData.balance;
      subData['wxpayAmount'] = this.data.orderSubData.wxpayAmount;
      if(this.data.usePayType.useBalance){
        if(this.data.orderSubData.wxpayAmount > 0){
          if(!this.data.usePayType.useBalanceAndWechat){
            // 提示余额不够支付当前订单，前往充值或使用微信继续支付。
            let self = this;
            wx.showModal({
              title: '余额不足',
              content: '您当前余额不足已支付本订单，请选择余额充值或使用微信支付',
              confirmText:'微信支付',
              cancelColor:'#576B95',
              cancelText:'立即充值',
              success (res) {
                if (res.confirm) {
                  self.setData({
                    'usePayType.useBalanceAndWechat': true
                  })
                  self.preparePay();
                } else {
                  self.jumpToWallet();
                }
              }
            })
            return;
          }
        }
      }
      if(this.data.orderSubData.wxpayAmount > 0){
        if(!this.data.usePayType.useBalance && !this.data.usePayType.useWechat){
          app.alert('请选择支付方式');
          return;
        }
      }
      app.sHttp.reportOrderCreate(subData).then(res =>{
        let self = this;
        if(res.result.orderStatus == 1){
          this.payOk('提交完成','您当前订单提交完成，请等待报告结果');
        }else{
          if(Object.hasOwnProperty.call(res.result, 'payInfo')){
            this.setData({
                'orderInfo.orderNo': res.result.orderNo,
                'orderInfo.orderStatus': res.result.orderStatus,
                'orderInfo.payInfo': res.result.payInfo
            }, () => {
                self.tuneUpPay();
            });
          }else{
            this.payOk('提交完成','您当前订单提交完成，请等待报告结果');
          }
        }
      },err=>{
        app.error(err.msg);
      })
    } catch (error) {
      app.alert('订单信息不完整,请关闭重试。');
    }
  },    
  tuneUpPay(){
    // 从Data里面拿参数
    let orderInfo = this.data.orderInfo;
    try {
      if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
        app.alert('支付参数不完整');
        return;
      };
      // 吊起支付。
      let self = this;
      wx.requestPayment({
          timeStamp: orderInfo.payInfo.timeStamp,
          nonceStr: orderInfo.payInfo.nonceStr,
          package: orderInfo.payInfo.package,
          signType: orderInfo.payInfo.signType,
          paySign: orderInfo.payInfo.paySign,
          success (res) {
              // 查询订单完成信息。
              let _this = self;
              app.showLoading('查询订单状态');
              setTimeout(() => {
                  wx.hideLoading();
                  _this.OrderPayResult();
              }, 5000);
          },
          fail (res) {
            self.payOk('支付失败','您已取消支付，可在订单列表中选择继续支付');
          }
      })
    } catch (error) {
      app.alert('支付参数不完整');
    }
  },
  OrderPayResult(){
      let orderInfo = this.data.orderInfo;
      if ('' == orderInfo.orderNo) {
          app.alert('支付参数不完整');
          return;
      };
      app.sHttp.reportOrderPayResult(orderInfo.orderNo).then(res =>{
          let orderStatus = res.orderStatus;
          if (0 == orderStatus) {
              this.payOk('查询结果','请等待几分钟后在订单列表中查看订单状态，如长时间未显示成功状态，请联系客服处理');
              return;
          }else if (1 == orderStatus) {
              this.payOk('提交完成','您当前订单提交完成，请等待报告结果');
              return;
          }else{
            this.payOk('查询结果','请等待几分钟后刷新查看，如长时间未显示成功状态，请联系客服处理');
          }
      },err=>{
        app.error(err.msg);
      })
  },
  payOk(title,content){
    let self = this;
    wx.showModal({
      title: title,
      content: content,
      confirmText: '我知道了',
      showCancel: false,
      success(res) {
          self.GoToOrder();
      }
    })
  },
  GoToOrder(){
    wx.redirectTo({
      url: '/pages/carQueryRecord/carQueryRecord'
    })
  },
  BackPage() {
    var that = this;
    wx.navigateBack({
      delta: 1,
      fail: function(){
        that.toHome();
      }
    });
  },
  toHome(){
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  jumpToUserAgreement(){
    wx.navigateTo({
      url: '/pages/publicPage/userAgreement/userAgreement',
    })
  },
})